package com.clss.commandhelper.function.home;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;

import com.clss.commandhelper.CommandHelperApplication;
import com.clss.commandhelper.base.BaseJson;
import com.clss.commandhelper.net.ApiClient;
import com.clss.commandhelper.tools.Lg;
import com.clss.commandhelper.tools.SpHelper;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 上传当前位置
 * @author liuv
 * @date 2017/12/6
 */

public class UploadLocationService extends IntentService {
    private static final String TAG = "UploadLocationService";

    private static final String USE_APPLICATION_LOCATION = "USE_APPLICATION_LOCATION";
    private static final String USE_PRIVATE_LOCATION = "USE_PRIVATE_LOCATION";

    public static void startUploadLocation(Context context){
        Intent intent = new Intent(context, UploadLocationService.class);
        intent.setAction(USE_APPLICATION_LOCATION);
        context.startService(intent);
    }

    public static void startUploadLocation(Context context, double lng, double lat, String address){
        if (lng < 1 || lat < 1){
            return;
        }
        Intent intent = new Intent(context, UploadLocationService.class);
        intent.setAction(USE_PRIVATE_LOCATION);
        intent.putExtra("lng", lng);
        intent.putExtra("lat", lat);
        intent.putExtra("address", address);
        context.startService(intent);
    }

    public UploadLocationService() {
        super("UploadLocationService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent == null){
            return;
        }
        double lng = 0, lat = 0;
        String address = null;
        String action = intent.getAction();
        if (USE_APPLICATION_LOCATION.equals(action)){
            lng = CommandHelperApplication.getMapLocation().getLongitude();
            lat = CommandHelperApplication.getMapLocation().getLatitude();
            address = CommandHelperApplication.getMapLocation().getAddress();
        }else if (USE_PRIVATE_LOCATION.equals(action)){
            lng = intent.getDoubleExtra("lng", 0);
            lat = intent.getDoubleExtra("lat", 0);
            address = intent.getStringExtra("address");
        }

        Map<String, String> body = new HashMap<>(3);
        body.put("lng", lng + "");
        body.put("lat", lat + "");
        body.put("address", address);

        ApiClient.apiList.uploadLocation(SpHelper.getInstance().getToken(), body).enqueue(new Callback<BaseJson>() {
            @Override
            public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {
            }

            @Override
            public void onFailure(Call<BaseJson> call, Throwable t) {
            }
        });
    }
}
